/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
// bfs：层次遍历：每层保留最后一个节点；
func rightSideView(root *TreeNode) []int {
	if root == nil {
		return nil
	}

	var res []int

	var q []*TreeNode
	q = append(q, root)
	for len(q) > 0 {
		res = append(res, q[len(q)-1].Val)
		var tmp []*TreeNode
		for len(q) > 0 {
			n := q[0]
			q = q[1:]

			if n.Left != nil {
				tmp = append(tmp, n.Left)
			}
			if n.Right != nil {
				tmp = append(tmp, n.Right)
			}
		}
		q = tmp
	}

	return res
}